<template>
    <right-layout :title="title" :visible.sync="show" @closeLayout="closeLayout" :loading='loading2'
        class="layout-wrap">
        <el-form :model="ruleForm" :rules="rule" ref="ruleForm" label-width="160px" label-position="left" >
            <el-form-item label="标题:" prop="title">
                <el-input v-model="ruleForm.title"></el-input>
            </el-form-item>
            <el-form-item label="优先级:" prop="priority">
                <el-input-number size="medium" v-model="ruleForm.priority" :min="0" :step="1">
                </el-input-number>
            </el-form-item>
            <el-form-item label="描述:" prop="desc">
                <el-input type="textarea" v-model="ruleForm.desc" :rows="4"></el-input>
                <text-length v-model="ruleForm.desc" :length.sync="ruleForm.descr_l" :max="128"></text-length>
            </el-form-item>
            <el-form-item label="执行条件：">
                <selectCondition v-model="ruleForm.queryCond" :typeCodeIds="typeCodeIds" v-if="isselectCondition">
                </selectCondition>
            </el-form-item>
            <el-form-item label="触发动作：">
                <selectAction v-model="ruleForm.task" :typeCodeIds="typeCodeIds" v-if="isselectCondition">
                </selectAction>
            </el-form-item>
            <el-form-item label="状态：" prop="statusCode">
                <commCheckbox :options="sysParaObj['SP_STATSU_B']" v-model="ruleForm.statusCode"
                    :label.sync="ruleForm.statusName" defaultPara>
                </commCheckbox>
            </el-form-item>
        </el-form>
        <div slot="foot">
            <div class="left">
                <el-button type="text" @click="closeLayout">取消</el-button>
            </div>
            <el-button type="primary" @click="submitForm('ruleForm')" :loading="loading">保存</el-button>
            <el-button type="primary" @click="saveAndNew('ruleForm')" :loading="loading" v-if="!ruleForm.id">保存并新建
            </el-button>
            <el-button type="default" @click="resetForm">重置</el-button>
        </div>
    </right-layout>
</template>

<script>
    import FixBottomButton from '@/components/FixBottomButton';
    import RightLayout from '@/components/common/comp/RightLayout';
    import selectPara from '@/components/selectPara';
    import selectClassify from '@/components/selectClassify';
    import textLength from '@/components/textLength';
    import selectCondition from './selectCondition'
    import selectAction from './selectAction'
    import {
        getSysParaListByCodes
    } from '@/service/core/dictionary';
    import commCheckbox from '@/components/commCheckbox';
    import {
        getNewSaveFun,
        getByIdCfDateFun,
        getByIdCfDetailed
    } from '@/service/core/trigger/index.js';
    import {
        queryTreeClass
    } from '@/service/core/sysConfig';
    import {
        setTimeout
    } from 'timers';
    import {
        commPara
    } from '@/mixins/mixins'
    import {
        error
    } from 'util';
    export default {
        props: {
            typeIds: String,
            typeCodeIds: String,
            typeNamesLike: String
        },
        mixins: [commPara],
        components: {
            FixBottomButton,
            RightLayout,
            selectPara,
            selectClassify,
            textLength,
            commCheckbox,
            selectCondition,
            selectAction
        },
        data() {
            var validate_descr = (rule, value, callback) => {
                if (this.ruleForm.descr_l > 128) {
                    callback(new Error());
                } else {
                    callback();
                }
            }
            return {
                show: false,
                title: '触发器新增',
                action: 'add',
                loading: false,
                isselectCondition: false,
                step: 0,
                sortable: null,
                options: [], //触发条件下拉项
                actions: [], //执行条件下拉项
                rule: {
                    title: [{
                            required: true,
                            message: '请输入标题',
                            trigger: 'blur'
                        },
                        {
                            min: 0,
                            max: 32,
                            message: '长度限制32位',
                            trigger: 'blur'
                        }
                    ],
                    priority: [{
                        required: true,
                        message: '请输入优先级',
                        trigger: 'blur'
                    }, {
                        pattern: /^[\w\W]{0,3}$/,
                        message: "长度限制0-3位",
                    }],
                    state: [{
                        required: true,
                        message: '请添加触发条件',
                        trigger: 'change'
                    }],
                    states: [{
                        required: true,
                        message: '请添加执行动作',
                        trigger: 'change'
                    }],
                    desc: [{
                        validator: validate_descr,
                        message: '长度限制128字',
                        trigger: 'blur'
                    }, ],
                    statusCode: [{
                        required: true,
                        message: '请选择状态',
                        trigger: 'blur'
                    }],
                    field: [{
                        required: true,
                        message: '请选择条件字段',
                        trigger: 'change'
                    }],
                    Multiple: [{
                        // required: true,
                        validator: (ruler, value, cb, source, option) => {
                            let index = ruler.field.split('.')[1];
                            let row = this.ruleForm.tgCont[index];
                            if (!row.startVal && !row.endVal) {
                                cb('请输入至少一个选项');
                            } else {
                                cb();
                            }
                        },
                        message: '请填选多个选项',
                        trigger: 'blur'
                    }],
                    Multiples: [{
                        required: true,
                        message: '请填选多个选项',
                        trigger: 'change'
                    }],
                    conditions: [{
                        required: true,
                        message: '请选择触发条件',
                        trigger: 'change'
                    }],
                    cond: [{
                        required: true,
                        message: '请选择触发条件',
                        trigger: 'change'
                    }]
                },
                ruleForm: { //触发条件
                    id: '',
                    code: '',
                    title: '', // 标题
                    desc: '', //描述
                    tgCont: [], // 触发事件集合
                    descr_l: 0,
                    tgConts: [], //执行动作集合
                    cond: '',
                    codes: '',
                    endVal: '',
                    fieldCode: '',
                    queryCond: [],
                    task: [],
                    fieldName: '',
                    opeCode: '',
                    opeName: '',
                    startVal: '',
                    priority: '',
                    statusCode: '',
                    statusName: ''
                },
                condition: { //触发条件
                    key: '',
                    fieldCode: '',
                    fieldName: '',
                    opeCode: '',
                    opeName: '',
                    startVal: [],
                    endVal: [],
                    casOpt: [],
                    keyString: ''
                },
                actionDate: { //执行条件
                    key: '',
                    fieldCode: '',
                    startVal: [],
                    valName: [],
                    keyString: '',
                },
                sysParaObj: {
                    'SP_STATSU_B': [],
                },
                taske: [],
                condis: [],
                loading2: false,
                loading3: false
            }
        },

        methods: {
            resetForm() { //重置
                if (!this.ruleForm.id) {
                    this.$nextTick(() => {
                        this.ruleForm.queryCond = []
                        this.ruleForm.task = []
                        this.$refs.ruleForm.resetFields();
                        this.ruleForm.statusCode = ''
                        this.sysParaObj = JSON.parse(JSON.stringify(this.sysParaObj)); // 默认参数反显
                    })
                } else {
                    this.ruleForm.queryCond = []
                    this.ruleForm.task = []
                    this.queryTriggerFun();
                }
            },

            showLayout(data) {
                if (data) {
                    this.title = '触发器编辑';
                    this.action = 'edit';
                    this.ruleForm.id = data.id;
                    this.queryTriggerFun()
                } else {
                    this.title = '触发器新增';
                    this.action = 'add';
                    this.ruleForm.id = '';
                    this.refreshC()
                }
                this.show = true;
            },
            refreshC() {
                this.isselectCondition = false;
                this.$nextTick(() => {
                    this.isselectCondition = true
                })
            },
            queryTriggerFun() { //获取查询表格数据
                let params = {
                    id: this.ruleForm.id
                }
                getByIdCfDetailed(params).then(res => {
                    if (res.data.code == 1000) {
                        let data = res.data.data
                        this.ruleForm.id = data.id
                        this.ruleForm.title = data.title
                        this.ruleForm.priority = data.priority
                        this.ruleForm.desc = data.descr
                        this.ruleForm.statusCode = data.statusCode
                        this.ruleForm.statusName = data.statusName
                        this.ruleForm.queryCond = []
                        this.ruleForm.task = []
                        if (data.queryCond) {
                            this.ruleForm.queryCond = JSON.parse(data.queryCond)
                        }
                        if (data.task) {
                            this.ruleForm.task = JSON.parse(data.task)
                        }
                        this.refreshC()
                    }
                })
            },

            submitForm(formName) { //保存

                this.ruleForm.queryCond.forEach((i) => {
                    for (let j = 0; j < i.items.length; j++) {
                        delete i.items[j].thirdArr
                        delete i.items[j].casOpt
                    }
                })
                this.ruleForm.task.forEach((i) => {
                    for (let j = 0; j < i.items.length; j++) {
                        delete i.items[j].thirdArr
                        delete i.items[j].casOpt
                    }
                })

                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let params = {
                            id: this.ruleForm.id,
                            title: this.ruleForm.title,
                            descr: this.ruleForm.desc,
                            priority: this.ruleForm.priority,
                            statusCode: this.ruleForm.statusCode,
                            statusName: this.ruleForm.statusName,
                            typeIds: this.typeIds,
                            typeNames: this.typeNamesLike,
                            queryCond: this.ruleForm.queryCond.length ? JSON.stringify(this.ruleForm
                                .queryCond) : '',
                            task: this.ruleForm.task.length ? JSON.stringify(this.ruleForm
                                .task) : '',
                        }

                        this.loading = true;
                        getNewSaveFun(params).then(res => {
                            if (res.data.code == 1000) {
                                this.$notify({
                                    title: '提示',
                                    type: 'success',
                                    message: '保存成功！'
                                })
                                this.$emit('refresh');
                                this.closeLayout();
                            }
                            this.loading = false;
                        }).catch(error => {
                            this.loading = false;
                        })

                    } else {
                        return false;
                    }
                });
            },
            saveAndNew(formName) { //保存

                this.ruleForm.queryCond.forEach((i) => {
                    for (let j = 0; j < i.items.length; j++) {
                        delete i.items[j].thirdArr
                        delete i.items[j].casOpt
                    }
                })
                this.ruleForm.task.forEach((i) => {
                    for (let j = 0; j < i.items.length; j++) {
                        delete i.items[j].thirdArr
                        delete i.items[j].casOpt
                    }
                })

                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let params = {
                            id: this.ruleForm.id,
                            title: this.ruleForm.title,
                            descr: this.ruleForm.desc,
                            priority: this.ruleForm.priority,
                            statusCode: this.ruleForm.statusCode,
                            statusName: this.ruleForm.statusName,
                            typeIds: this.typeIds,
                            typeNames: this.typeNamesLike,
                            queryCond: this.ruleForm.queryCond.length ? JSON.stringify(this.ruleForm
                                .queryCond) : '',
                            task: this.ruleForm.task.length ? JSON.stringify(this.ruleForm
                                .task) : '',
                        }

                        this.loading = true;
                        getNewSaveFun(params).then(res => {
                            if (res.data.code == 1000) {
                                this.$notify({
                                    title: '提示',
                                    type: 'success',
                                    message: '保存成功！'
                                })
                                this.$emit('refresh');
                                this.closeLayout1();
                            }
                            this.loading = false;
                        }).catch(error => {
                            this.loading = false;
                        })

                    } else {
                        return false;
                    }
                });
            },
            closeLayout1() {
                this.ruleForm.id = '';
                setTimeout(() => {
                    this.resetForm();
                }, 500)
            },
            closeLayout() { //取消
                this.$nextTick(() => {
                    this.ruleForm.queryCond = []
                    this.ruleForm.task = []
                    this.$refs.ruleForm.resetFields();
                    this.sysParaObj = JSON.parse(JSON.stringify(this.sysParaObj)); // 默认参数反显
                })
                this.show = false

            },
        },

    }
</script>

<style lang="scss" scoped>
    .right-layout {
        .elform {
            background: #fff;

            /deep/ .mb10 {
                padding-top: 5px;
                border: solid 1px #eee;
            }

            /deep/ .select1 {
                margin: 4px 5px;
            }

            /deep/ .remove-wrap {
                margin-top: 4px;
                text-align: center
            }
        }
    }

    .noShow {
        display: none;
    }
</style>